import React from 'react';
import { getImg } from '../../../tool/file';
import Transition from '../../transition';
import style from './style.module.less';

// 动态加载
const Zmage = React.lazy(() => import('react-zmage'));

interface IProps {
  src: string;
  className?: string;
  preview?: boolean;
  [key: string]: any;
}

interface IState {
  src: string;
  err: boolean;
  imgStyle: React.CSSProperties;
  previewStyle: React.CSSProperties;
}

export default class Img extends React.Component<IProps, IState> {
  box?: HTMLDivElement | null;

  state = {
    src: '',
    err: false,
    imgStyle: {},
    previewStyle: {},
  };

  componentDidMount() {
    this.load();
  }

  // 图片加载后显示出最短边
  load = async () => {
    try {
      this.setState({ err: false });
      const { src, width, height } = await getImg(this.props.src);
      const box = this.box!;
      const widthRatio = width / (box.clientWidth || width);
      const heightRatio = height / (box.clientHeight || height);
      const ratio = widthRatio > heightRatio;
      const imgRatio = ratio ? heightRatio : widthRatio;
      const previewRatio = !ratio ? heightRatio : widthRatio;
      this.setState({
        src,
        imgStyle: {
          width: width / imgRatio,
          height: height / imgRatio,
        },
        previewStyle: {
          width: width / previewRatio,
          height: height / previewRatio,
        },
      });
    } catch (e) {
      this.setState({ err: true });
    }
  };

  render() {
    const { src, className, preview, ...props } = this.props;
    const { err, imgStyle, previewStyle, ...state } = this.state;
    let main: JSX.Element = <div key="loading" className={`fill center loading ${style.loading}`} />;
    if (err) {
      main = (
        <div key="err" className={`fill center ${style.err}`}>
          <span onClick={this.load}>重新加载</span>
        </div>
      );
    } else if (state.src) {
      main = (
        <>
          <img key="img" style={imgStyle} className={preview ? style.preview : undefined} {...state} />
          {preview && (
            <div key="preview" className="fill center">
              <React.Suspense fallback={<div className="loading" />}>
                <Zmage radius={0} style={previewStyle} {...state} />
              </React.Suspense>
            </div>
          )}
        </>
      );
    }
    return (
      <div className={`center ${style.box} ${className}`} ref={box => (this.box = box)} {...props}>
        <Transition name="fade">{main}</Transition>
      </div>
    );
  }
}

